using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using SmartLink.DTOS;
using SmartLink.DTOS;
using SmartLink.EnumLibrary;
using SmartLink.Infrastructure;
using SmartLink.Infrastructure.Cache;

namespace SmartLink.WebApi.Filter
{
    /// <summary>
    /// 首次登陆检验
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class FirstLoginCheckAttribute : ActionFilterAttribute
    {
        private bool _enabled;

        public FirstLoginCheckAttribute(bool enabled = true)
        {
            _enabled = enabled;
        }

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0
                   || actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0)
            {
                return;
            }

            if (_enabled == false)
            {
                return;
            }

            //if (HasUpdatedPwdSelf(actionContext) == false)
            //{
            //    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden,
            //                             new Results { State = (int)StateCodeEnum.首次登陆强制修改密码, Message = "您的账号首次登陆，请修改密码！" });
            //    return;
            //}
        }

        private bool HasUpdatedPwdSelf(HttpActionContext actionContext)
        {
            string token = actionContext.Request.Headers.GetValues("token").FirstOrDefault();
            if (string.IsNullOrWhiteSpace(token))
                return false;
            var userId = JWTHelper.GetUserIdFromToken(token);
            var user = UserInfoCaches.GetUserInfoCache(userId);
            return user.HasUpdatedPwdSelf;
        }
    }
}